package org.foreningsgatan.modular.lightsources;

import java.util.ArrayList;
import java.util.List;

/**
 * 
 * Copyright (c) 2008 Joakim Back
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 * 
 * @author Joakim Back
 *
 * @param <T>
 */
public class Renderer<T extends LightSource> {
	private SourceHandler sourceHandler;

	private SourceTables sourceTables;

	private LightMap staticLights;

	private RGB ambientLight = new RGB(0.0f, 0.0f, 0.0f);

	public void setStaticLights(LightMap staticLights) {
		this.staticLights = staticLights;
	}

	public Renderer(SourceHandler handler, SourceTables sourceTables) {
		this.sourceHandler = handler;
		this.sourceTables = sourceTables;
	}

	/**
	 * Calculate Intensity based on distance from light source
	 * 
	 * @param x1
	 * @param y1
	 * @param x2
	 * @param y2
	 * @param range
	 * @return
	 */
	public static float calcIntensity(double x1, double y1, double x2,
			double y2, double range) {
		double distance = CommonMath.distance(x1, y1, x2, y2);

		if (distance <= range) {
			return (float) Math.pow(1.0 - (distance / range), 2);
		} else {
			return 0f;
		}
	}

	/**
	 * Filter light sources outside the rendered area
	 * 
	 * @param size
	 * @param offsetX
	 * @param offsetY
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private List<T> relevantSources(int size,
			double offsetX, double offsetY, boolean ignoreStatic) {
		List<T> relevant = new ArrayList<T>();

		for (LightSource source : sourceHandler.getSources()) {
			if ((!ignoreStatic) || (source.getType() != CacheType.STATIC)) {
				boolean inX = CommonMath.overlap(source.getX()
						- source.getRange(), source.getX() + source.getRange(),
						offsetX, offsetX + size);
				boolean inY = CommonMath.overlap(source.getY()
						- source.getRange(), source.getY() + source.getRange(),
						offsetY, offsetY + size);

				if (inX && inY) {
					relevant.add((T) source);
				}
			}
		}

		return relevant;
	}

	/**
	 * Blend light sources at coordinate
	 * 
	 * @param sources
	 * @param x
	 * @param y
	 * @param useCache
	 * @return
	 */
	private RGB blendSources(List<? extends LightSource> sources, int x,
			int y, boolean useCache) {
		RGB rgb = (useCache) ? staticLights.get(x, y) : null;

		if (rgb != null) {
			rgb = rgb.clone();
		} else {
			rgb = ambientLight.clone();
		}

		for (LightSource source : sources) {
			if (CommonMath.within(x, source.getX() - source.getRange(), source
					.getX()
					+ source.getRange())
					&& CommonMath.within(y, source.getY() - source.getRange(),
							source.getY() + source.getRange())) {
				RGB add;

				if (sourceTables.contains(source)) {
					add = sourceTables.get(source, x - source.getX(), y
							- source.getY());
				} else {
					float intensity = calcIntensity(x, y, source.getX(), source
							.getY(), source.getRange());

					add = source.getSource().clone();

					add.multiply(intensity);
				}

				rgb.add(add);
			}
		}

		return rgb;
	}

	/**
	 * Render LightMap
	 * 
	 * @param sources
	 * @param size
	 * @param offsetX
	 * @param offsetY
	 * @param useCache
	 * @return
	 */
	protected LightMap render(List<? extends LightSource> sources, int size,
			int offsetX, int offsetY, boolean useCache, boolean includeOffset) {
		LightMap map = new LightMap(size);
		
		if (includeOffset) {
			map.applyOffset(offsetX, offsetY);
		}

		for (int y = 0; y < size; y++) {
			for (int x = 0; x < size; x++) {
				RGB rgb = blendSources(sources, offsetX + x, offsetY + y,
						useCache);

				map.set(x, y, rgb);
			}
		}

		return map;
	}

	public void setAmbientLight(RGB ambientLight) {
		this.ambientLight = ambientLight.clone();
	}

	/**
	 * Render LightMap
	 * 
	 * @param size
	 * @param offsetX
	 * @param offsetY
	 * @return
	 * @throws Exception
	 */
	public LightMap render(int size, int offsetX, int offsetY, boolean includeOffset)
			throws Exception {
		if (staticLights == null) {
			throw new Exception("Static lights has not been initialized.");
		}

		List<? extends LightSource> sources = relevantSources(size, offsetX,
				offsetY, true);

		LightMap map = render(sources, size, offsetX, offsetY, true, includeOffset);

		return map;
	}

	public List<T> getLightSources(int size,
			double offsetX, double offsetY) {
		return relevantSources(size, offsetX, offsetY, false);
	}
}
